

import React, { useEffect, useState, useRef } from 'react'
import { Input, Select, Table, Pagination, Spin, Space, Form, Button, Modal, Radio, message } from 'antd';
import { useSelector, useDispatch, Link, ProdTagModelState } from "umi";
import styles from './index.less'
import { getProdTag, getSerachList, getisSerach, getAddProdLsit, getDeleteListItem, getPUTListItem, getPaging } from '@/services'
import {
  AppstoreOutlined,
  DeleteOutlined,
  EditOutlined,
  SearchOutlined,
  SyncOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined
} from '@ant-design/icons';
import _ from 'lodash'

import Paging from '@/components/paging'

const prodTag = () => {
  const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;
  const dispatch = useDispatch()
  const { Option } = Select;
  const [isFlag, setIsFlag] = useState(true); //搜索框隐藏
  const [prodlist, setProdList] = useState()//默认数据
  const [serachList, setSerachList] = useState() //搜索数据
  const [istext, setistext] = useState(0) //下拉
  const inputEl = useRef(null); //input
  const [isModalVisible, setIsModalVisible] = useState(false);//对话框-新增
  const [isModalVisibles, setIsModalVisibles] = useState(false);//对话框-编辑
  const [value, setValue] = React.useState(1);//状态-单选框
  const [values, setValues] = React.useState(0);//列表样式-单选框
  const inputName = useRef(null); //新增-标签名称input
  const inputSort = useRef(null); //新增-排序input 
  const [isModalVisibleFlag, setIsModalVisibleFlag] = useState(false);//显隐
  const [nameValue, setProdName] = useState('')//编辑
  const [sortValue, setProdSort] = useState('')//编辑
  const [putValue, setputValue] = React.useState(0);//编辑状态-单选框
  const [putValues, setputValues] = React.useState(0);//编辑列表样式-单选框
  const [putID, setPutID] = useState('')//编辑id
  let [pagingList, setPagingList] = useState()//分页
  let [ListLength, setListLength] = useState(0)//分页
  console.log(prodlist);

  const [form] = Form.useForm();
  // const { prodTagList } = useSelector((state: { prodprodTag: any }) => state.prodprodTag);
  // console.log( '页面', prodTagList);

  // 默认数据-方法
  async function getsetProdList() {
    await getProdTag().then((res) => {
      // 解决key报错，加上序号
      let datas = res.records.map((item: any, index: any) => {
        return { key: index + 1, ...item }
      })
      setProdList(datas)
    })
  }
  useEffect(() => {
    // dispatch({
    //   type: 'prodprodTag/getProdTagList'
    // })
    // dispatch({
    //   type: 'prodprodTag/getSerachProdTagList'
    // })
    getsetProdList()
  }, [])
  console.log(prodlist, pagingList);
  // 头部搜索框显示隐藏
  function changeFlag() {
    setIsFlag(!isFlag)
  }
  // 刷新
  function refresh() {
    getsetProdList()
  }
  // 搜索
  async function prodSerach() {
    // 输入框的值
    let text = (inputEl as any).current.input.value
    // 搜索接口
    if (text !== '') {
      await getSerachList(text).then((res) => {
        setSerachList(res.records)
      })
    } else {
      await getisSerach(istext).then((res) => {
        console.log(res);
        setSerachList(res.records)
      })
    }
  }
  function isValuesChange(value: any) {
    if (value) {
      let istext = value === '正常' ? 1 : 0
      setistext(istext)
    }
  }
  // 清空
  function inputEmpty() {
    window.location.href = '/prod-prodTag'
  }

  // 新增
  const showModal = () => {
    setIsModalVisible(true);
  };
  // 新增确认
  const handleOk = async () => {
    let isinputName = (inputName as any).current.input.value
    let isflag = isinputName.length > 0 ? false : true

    setIsModalVisible(isflag);
    let payload = {
      id: new Date().getTime().toString().slice(-2),
      isDefault: null,
      prodCount: null,
      seq: (inputSort as any).current.input.value,
      shopId: 1,
      status: value,
      style: values,
      t: 1652353594400,
      title: (inputName as any).current.input.value
    }
    console.log((inputName as any).current.input.value);
    console.log((inputSort as any).current.input.value);
    console.log(new Date().getTime().toString().slice(-2));
    // 新增接口
    if (isflag === false) {
      await getAddProdLsit(payload).then((res) => {
        console.log(res);
      })
      getsetProdList()
      message.success('新增成功')
    }
  };
  // 新增取消
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  function onFinish(values: any) {
    console.log('Success:22222', values);
  };

  function onFinishFailed(errorInfo: any) {
    console.log('Failed:11111', errorInfo);
  };
  // 单选框
  const onChange = (e: any) => {
    // setRadioA(e.target.value)
    console.log('radio checked', e.target.value);
    setValue(e.target.value);
    console.log(value);

  };
  // 单选框2
  const onChanges = (e: any) => {
    console.log('radio checked', e.target.value);
    setValues(e.target.value);
  };


  // 显隐
  function KillQQAd() {
    setIsModalVisibleFlag(true)
  }
  function isKillQQAd() {
    setIsModalVisibleFlag(false)
  }

  // 删除 
  function prodDelete(id: any) {
    console.log(id, 'id-----');
    Modal.confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: '确认进行删除操作？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => deleteOk(id),
      onCancel: deleteFalse
    });

  }
  // 删除确认
  async function deleteOk(id: string) {
    if (id) {
      await getDeleteListItem(id).then((res => {
        console.log(res);
      }))
      getsetProdList()
      message.success('删除成功')
    } else {
      message.success('参数错误')
    }
  }
  function deleteFalse() {
    console.log(123123123);
  }
  // 修改
  function prodPut(prodlist: any) {
    console.log(prodlist.id, '--=====');
    setPutID(prodlist.id)
    setProdName(prodlist.title)
    setProdSort(prodlist.seq)
    setputValue(prodlist.status)
    setputValues(prodlist.style)
    setIsModalVisibles(true);
  }
  // // 修改确认
  async function putOk() {
    setIsModalVisibles(false);
    console.log(nameValue, sortValue, putValue, putValues);
    let payload = {
      createTime: "2022-05-13 16:40:29",
      deleteTime: null,
      id: putID,
      isDefault: 0,
      prodCount: 0,
      seq: sortValue,
      shopId: 1,
      status: putValue,
      style: putValues,
      t: new Date().getTime() + 0,
      title: nameValue,
      updateTime: "2022-05-13 17:53:14",
    }
    await getPUTListItem(payload).then((res) => {
      console.log(res);
    })
    getsetProdList()
  }
  // 修改取消
  function putCancel() {
    setIsModalVisibles(false);
  }
  // 监听input title的值
  function changeValue(nameValue: any) {
    setProdName(nameValue.target.value)
  }
  // 监听input sort的值
  function changeValueSort(nameValueSort: any) {
    setProdSort(nameValueSort.target.value)
  }
  // 修改多选框
  function addonChange(putValue: any) {
    setputValue(putValue.target.value)
  }
  // 修改多选框
  function addonChanges(putValues: any) {
    setputValues(putValues.target.value)
  }
  // 分页

  async function onChangelist(pageNumber: any) {
    let params = {
      t: '1652684940187',
      current: pageNumber,
      page: 10
    }
    await getPaging(params).then((res) => {
      let datas = res.records.map((item: any, index: any) => {
        return { key: index + 1, ...item }
      })
      setPagingList(datas)
      setListLength(res.total);
    })
  }

  function onShowSizeChange(current: any,size: any){
    console.log(current,size);
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'id',
      align: "center",
    },
    {
      title: '标签名称',
      dataIndex: 'title',
      key: 'id',
      align: "center",
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'id',
      align: "center",
      render: (status: number) => {
        return status === 1 ? <span className={styles.normal}>正常</span> : <span className={styles.disables}>禁用</span>
      }
    },
    {
      title: '默认类型',
      key: 'id',
      dataIndex: 'isDefault',
      align: "center",
      render: (isDefault: string) => {
        return (isDefault ? <span className={styles.typesItem}>默认类型</span> : <span className={styles.typesItem}>自定义类型</span>)
      }
    },
    {
      title: '排序',
      dataIndex: 'seq',
      key: 'id',
      align: "center",
    },
    {
      title: '操作',
      dataIndex: 'id',
      key: 'shopid',
      align: "center",
      render: (text: any, prodlist: any) => {
        return (
          <Space size="middle">
            <div className={styles.revise}>
              <EditOutlined />
              <span onClick={() => { prodPut(prodlist) }}>&nbsp;修改</span>
            </div>
            <div className={styles.remove}>
              <DeleteOutlined />
              <span onClick={() => { prodDelete(prodlist.id) }}>&nbsp;删除</span>
            </div>
          </Space>
        )
      },
    },
  ];


  let data = prodlist
  return (
    <div className={styles.prodTag}>
      <div className={isFlag === true ? styles.serach : styles.serachNull}>
        <div className={styles.serachName}>
          <span>标签名称</span><Input ref={inputEl} placeholder="标签名称" />
        </div>
        <div className={styles.serachStatus}>
          <span className={styles.spans}>状态</span>
          <Form.Item style={{ width: '200px' }} >
            <Select
              onChange={isValuesChange}
              placeholder="状态"
              allowClear
            >
              <Option value="禁用">禁用</Option>
              <Option value="正常">正常</Option>
            </Select>
          </Form.Item>
        </div>
        <div className={styles.serachitem}>
          <SearchOutlined />
          {/*-------------- 防抖------------ */}
          <span onClick={_.debounce(prodSerach, 2000)}>&nbsp;搜 索</span>
        </div>
        <div className={styles.empty}>
          <DeleteOutlined />
          <span onClick={inputEmpty}>&nbsp;清空</span>
        </div>
      </div>
      <div className={styles.add}>
        <button onClick={showModal}><i>+</i> 新增</button>
        <Modal title="新增" okText='确认' cancelText='取消' visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
          <Form
            name="basic"
            initialValues={{ remember: false }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="标签名称"
              name="username"
              rules={[{ required: true, message: '标签名称不能为空!' }]}
            >
              <Input ref={inputName} />
            </Form.Item>
          </Form>
          <div className={styles.RadioA}>
            <span>状态</span>
            <Radio.Group onChange={onChange} value={value}>
              <Radio value={1}>正常</Radio>
              <Radio value={0}>禁用</Radio>
            </Radio.Group>
          </div>
          <div className={styles.RadioB}>
            <span className={styles.RadioBa}>列表样式</span>
            <Radio.Group onChange={onChanges} value={values}>
              <Radio value={0}>一列一个</Radio>
              <Radio value={1}>一列两个</Radio>
              <Radio value={2}>一列三个</Radio>
            </Radio.Group>
          </div>
          <div className={styles.RadioC}>
            <Form.Item
              label="排序"
            >
              <Input ref={inputSort} />
            </Form.Item>
          </div>
        </Modal>
        <div className={styles.icons}>
          <div onClick={refresh}><SyncOutlined /></div>
          <div onClick={KillQQAd}><AppstoreOutlined /></div>
          <Modal title="多 选" visible={isModalVisibleFlag} onCancel={isKillQQAd} footer={null}>
            <div className={styles.isModalVisibleFlag}>
              <div>
                <div>
                  <input type="checkbox" /> <span>隐藏</span>
                </div>
                <p>暂无数据</p>
              </div>
              <div>
                <span> 〈 </span>
                <span> 〉 </span>
              </div>
              <div>
                <div>
                  <input type="checkbox" /> <span>显示</span>
                </div>
                <p>
                  <input type="checkbox" /> <span>标签名称</span>
                </p>
                <p>
                  <input type="checkbox" /> <span>状态</span>
                </p>
                <p>
                  <input type="checkbox" /> <span>默认类型</span>
                </p>
                <p>
                  <input type="checkbox" /> <span>排序</span>
                </p>
              </div>
            </div>
          </Modal>
          <div onClick={changeFlag}><SearchOutlined /></div>
        </div>
      </div>
      <div className={styles.from}>
        <div>
          {
            pagingList == undefined ? <Table pagination={false} bordered={true} columns={columns} dataSource={serachList ? serachList : prodlist} />
              : <Table pagination={false} bordered={true} columns={columns} dataSource={serachList ? serachList : pagingList} />
          }

        </div>
        {/* 分页 */}
        <div className={styles.paging}>
          <span>共 {8} 条</span><Pagination showLessItems showQuickJumper defaultCurrent={1} total={200} onShowSizeChange={onShowSizeChange} onChange={onChangelist} />
        </div>
      </div>
      {/* 修改 */}
      <Modal title="新增" okText='确认' cancelText='取消' visible={isModalVisibles} onOk={putOk} onCancel={putCancel}>
        <Form
          name="basic"
          initialValues={{ remember: false }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="标签名称"
            rules={[{ required: true, message: '标签名称不能为空!' }]}
          >
            <Input value={nameValue} ref={inputName} onChange={(nameValue) => { changeValue(nameValue) }} />
          </Form.Item>
        </Form>
        <div className={styles.RadioA}>
          <span>状态</span>
          <Radio.Group onChange={(putValue) => addonChange(putValue)} value={putValue}>
            <Radio value={1}>正常</Radio>
            <Radio value={0}>禁用</Radio>
          </Radio.Group>
        </div>
        <div className={styles.RadioB}>
          <span className={styles.RadioBa}>列表样式</span>
          <Radio.Group onChange={(putValues) => addonChanges(putValues)} value={putValues}>
            <Radio value={0}>一列一个</Radio>
            <Radio value={1}>一列两个</Radio>
            <Radio value={2}>一列三个</Radio>
          </Radio.Group>
        </div>
        <div className={styles.RadioC}>
          <Form.Item
            label="排序"
          >
            <Input value={sortValue} ref={inputSort} onChange={(sortValue) => { changeValueSort(sortValue) }} />
          </Form.Item>
        </div>
      </Modal>
    </div>
  );
}
export default prodTag